package com.example.newsSys.config;

import com.example.newsSys.interceptor.LoginInterceptor;
import com.example.newsSys.json.JacksonObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;


/**
 * 配置类，注册web层相关组件
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    // 构造器注入 优于@Autowired注解注入
    private final LoginInterceptor loginInterceptor;

    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册管理端拦截器...");
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/admin/**");
    }
    // 静态资源映射 意为 static路径下的所有静态资源均可被访问
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        log.info("开始注册静态资源映射");
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("扩展mvc框架的消息转换器");
        // 创建一个消息转换器对象
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器 可以将java对象转换为json字符串 其中JSONObjectMapper是自定义的，继承自ObjectMapper
        converter.setObjectMapper(new JacksonObjectMapper());
        // 将我们自己的转换器放入spring MVC框架的容器中
        converters.add(0, converter);
    }
}
